<?php

namespace app\admin\controller\agent;

use app\admin\model\Admin;
use app\admin\model\Admininfo;
use app\admin\model\agent\Bill;
use app\admin\model\Githouse;
use app\admin\model\Preproduct;
use app\common\controller\Backend;
use app\common\model\Agent;
use app\common\model\Delivery;
use app\common\model\DeliveryGoods;
use app\common\model\order\Orderitem;
use app\common\model\Warehouse;
use http\Client;
use PHPExcel;
use think\Db;
use think\Session;
use workflow\workflow;
use app\admin\model\AuthDepartment;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Orderfen extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;
    protected $modelDelivery = null;
    protected $Orderitem = null;
    protected $Orderlog = null;
    protected $Githouse = null;
    protected $modelGithouse = null;
    protected $searchFields = "id,nb";
    protected $modelValidate = true;
    protected $modelSceneValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        //Orderlog  Orderitem Githouse
        $this->model = new \app\common\model\order\Order;
        $this->modelDelivery = new \app\common\model\Delivery;
        $this->Orderitem = new \app\common\model\order\Orderitem;
        $this->Orderlog = new \app\common\model\order\Orderlog;
        $this->Githouse = new Warehouse();
        $this->WorkFlow = new workflow();
        $this->modelGithouse = new Githouse();
        $dep = collection($this->modelGithouse->where("dep!=1")->order('id asc')->select())->toArray();

        $this->assign("dep",$dep);
        $this->view->assign('agentList',Agent::AgentList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
      
        //当前是否为关联查询
//        $this->relationSearch = true;
        $this->searchFields = 'id,nameAgent';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $fi_where = ['sorter'=>1]; 
            $total = $this->model
                ->where($where)
                ->where($fi_where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($fi_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            foreach ($list as &$value)
            {
                $value['userid_text'] =  Admin::userName($value['userid']);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 订单作废
     * @param string $ids
     * @throws \think\exception\DbException
     */
    public function can($ids = '')
    {
        if ($ids) {
            $pk = $this->model->getPk();
            //修改状态   添加库存
            $row = $this->model->where($pk, 'in', $ids)->find();
            Db::startTrans();
            //作废订单
            $row->status = 8;
            if(!$row->save())
            {
                Db::rollback();
            }
            $list = $this->Orderitem->where(['order_id'=>$ids])->select();
            $array = [];
            foreach ($list as $value)
            {
                //作废订单详情
                $value->status = 8;
                if(!$value->save())
                {
                    Db::rollback();
                    $this->error(__('没有可作废的数据！'));
                }
                $array[] = ['id'=>$value->preproduct_id,'num'=>$value->nums];
            }
            //判断是否出库 1= 已发货  0 = 待发货
            if($row->deliverystatus == 1 || $row->deliverystatus == 3)
            {
                //入库操作
                $agentName = Githouse::get(['dep'=>$row->dep_id]);
                $resout = gzy_fahuodan_zuofei($agentName->id,$array,$this->auth->userid);
                if(!$resout['status'])
                {
                    Db::rollback();
                    $preRow = Preproduct::get($resout['id']);
                    $this->error($preRow->cname.'入库失败！请联系管理员！');
                }else{
                    //订单修改订单日志 入库单id
                    $this->Orderlog->create([
                        'order_id'=>$ids,
                        'userid'=>$this->auth->userid,
                        'username'=>$this->auth->username,
                        'content'=>'订单'.$row->nb.'作废，入库单号'.$resout['order_id'],
                        'type'=>2,
                    ]);
                }
            }else{
                //订单修改订单日志 入库单id
                $this->Orderlog->create([
                    'order_id'=>$ids,
                    'userid'=>$this->auth->userid,
                    'username'=>$this->auth->username,
                    'content'=>'订单'.$row->nb.'作废',
                    'type'=>2,
                ]);
            }

            Db::commit();
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 统计详情
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function stat()
    {
        if($this->request->isAjax())
        {
            $createtime = $this->request->get('createtime');
            $where['sorter'] = 1;
            $where['nameAgent'] = $this->request->get('agent_name');
            if($createtime){
                $where['createtime'] = ['between time', [substr($createtime,0,19), substr($createtime,22,19)]];
            }
            $row = $this->model->field('group_concat(id) as ids')->where($where)->where('deliverystatus = 1 OR deliverystatus = 3 AND status != 8')->find();
            if(!$row->ids)
            {
                $this->error('没有数据！','','dadada');
            }
            $orderItem = collection($this->Orderitem->where('order_id','in',$row->ids)->field('id,sum(num) as num,preproduct_id,pricing,sum(real_ocean) as real_ocean,discount,sum(ministrial) as ministrial,status')->group('preproduct_id,discount')->select())->toArray();
            $this->success('查询成功！','',$this->statOrder($orderItem));
        }
        return $this->view->fetch();
    }

    public function statOrder($orderItem)
    {
        $html = "<div class=\"panel panel-default panel-intro panel-stat\">
            <div class=\"panel-body\">
                <div id=\"myTabContent\" class=\"tab-content\">
                        <table id=\"table1\" class=\"table table-striped table-bordered table-hover\" width=\"100%\">
                            <thead>
                            <tr>
                                <th>序号</th>
                                <th colspan=\"2\">产品名称</th>
                                <th>数量</th>
                                <th>定价</th>
                                <th>码洋</th>
                                <th>折扣</th>
                                <th>实洋</th>
                            </tr>
                            </thead>
                            <tbody>";
                            $num = 0;
                            $ministrial = 0;
                            $real_ocean = 0;
                           foreach ($orderItem as $key=>$value)
                           {
                               $html .= "<tr>
                                    <td>{$value['preproduct_id']}</td>
                                    <td colspan=\"2\"> {$value['preproductname_text']}</td>
                                    <td>{$value['num']}</td>
                                    <td>{$value['pricing']}</td>
                                    <td>{$value['ministrial']}</td>
                                    <td>{$value['discount']}</td>
                                    <td>{$value['real_ocean']}</td>
                                </tr>";
                                $num += $value['num'];
                                $ministrial += $value['ministrial'];
                                $real_ocean += $value['real_ocean'];
                           }
       $html .= "<tr>
                                <td colspan=\"2\" class=\"center\">合计数量：</td>
                                <td>$num/件</td>
                                <td colspan=\"2\" class=\"center\">合计码洋</td>
                                <td>$ministrial</td>
                                <td colspan=\"1\" class=\"center\">合计实洋</td>
                                <td>$real_ocean</td>
                            </tr>
                            </tbody>
                        </table>
                </div>
            </div>
        </div>";
        return $html;
    }

    /**
     * 详情
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($ids)
    {
        if($order = $this->model->get(['id'=>$ids,'sorter'=>1]))
        {
            if($order['idCard']){
                $order['idCard_text'] = Admin::userName($order['idCard']);
            }
            //订单详情
            $orderList = $this->Orderitem->alias('a')
                ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
                ->where('a.order_id',$ids)
                ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                ->select();
            $orderlogList = $this->Orderlog->where('order_id',$ids)->select();
            //审核记录
            $this->view->assign('flowLog',$this->WorkFlow->getLogApi($ids,'order'));
            $this->view->assign('orderlogList',$orderlogList);
            $this->view->assign('second',$this->request->request('second',0));
            $this->view->assign('order',$order);
            $this->view->assign('orderList',$orderList);
        }else{
            $this->error('数据不存在');
        }
        return $this->view->fetch();
    }

    public function download()
    {
        //查找代理商
        if($row = $this->request->request('row/a'))
        {
            $url = "/admin/agent/order_fen/eclipse?createtime={$row['createtime']}&cid={$row['cid']}&receivingWay={$row['receivingWay']}&forArrivalGoodsTime={$row['forArrivalGoodsTime']}&freightFor={$row['freightFor']}&remark={$row['remark']}";
            $this->success('',$url);
        }
        return $this->view->fetch();
    }

    /**
     * 发货单模板导出
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function eclipse()
    {
        //获取代理商信息
        $row = $this->request->request();
        $agent = Githouse::get(['id'=>$row['cid']]);
        //获取商品信息
        $list = Preproduct::where('type','=',2)->field('id,cname,price')->select();

        // 新建一个excel对象 大神已经加入了PHPExcel 不用引了 直接用！
        $objPHPExcel = new \PHPExcel();  //在vendor目录下 \不能少 否则报错
        // 设置文档的相关信息
        $objPHPExcel->getProperties()->setCreator("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单")/*设置作者*/
        ->setLastModifiedBy("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单")/*最后修改*/
        ->setTitle("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单")/*题目*/
        ->setSubject("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单")/*主题*/
        ->setDescription("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单")/*描述*/
        ->setKeywords("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单")/*关键词*/
        ->setCategory("北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单");/*类别*/
        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
        /*设置表头*/
        $objPHPExcel->getActiveSheet()->mergeCells('A1:H1');//合并第一行的单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A3:A6');//合并第二行的单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B5:B6');//合并第二行的单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C5:C6');//合并第二行的单元格
        $objPHPExcel->getActiveSheet()->mergeCells('D3:D6');//合并第二行的单元格
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单');//标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);      // 第一行的默认高度
        //第二行的内容和格式
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "日期");
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', $row['createtime']);
        $objPHPExcel->getActiveSheet()->getComment('F3')->getText()->createTextRun('背景为红色的，全部不能修改！');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', "发\n货\n方");
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B3', '名称');
        //    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', '业务员');
        // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', $row['userid']);
        // $objPHPExcel->getActiveSheet()->getComment('D2')->getText()->createTextRun('背景为红色的，全部不能修改！');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C3', '北京宏达一甲');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B4', '电话');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C4', '010-88878286');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B5', '地址');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C5', '北京市海淀区蓝靛厂东路2号金源商务中心B座3F');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D3', "收\n货\n方");
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', '分公司名称');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F3', $agent['gname']);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E4', '收货人');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F4', $agent['lxr']);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E5', '收货人电话');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F5', $agent['mobile']);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E6', '收货地址');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F6', $agent['address']);

        $objPHPExcel->getActiveSheet()->getStyle('A3:A6')->getAlignment()->setWrapText(true);//设置单元格允许自动换行
        $objPHPExcel->getActiveSheet()->getStyle('D3:D6')->getAlignment()->setWrapText(true);//设置单元格允许自动换行
        $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->getActiveSheet()->getStyle('A2:H2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->getActiveSheet()->getStyle('A3:H3')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->getActiveSheet()->getStyle('A4:H4')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->getActiveSheet()->getStyle('A5:H5')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->getActiveSheet()->getStyle('A6:H6')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->getActiveSheet()->getStyle('A7:H7')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);/*垂直居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A1:H1')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A2:H2')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A3:H3')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A4:H4')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A5:H5')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A6:H6')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A6:H7')->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        /*表头数据填充*/
        $objPHPExcel->setActiveSheetIndex(0)  //设置一张sheet为活动表 添加表头信息
            ->setCellValue('A7', '序号')
            ->setCellValue('B7', '产品名称')
            ->setCellValue('C7', '数量')
            ->setCellValue('D7', '定价')
            ->setCellValue('E7', '码洋')
            ->setCellValue('F7', '折扣')
            ->setCellValue('G7', '实洋')
            ->setCellValue('H7', '备注');
        // 关键数据
        $key = 8;
        foreach ($list as $value)
        {
            $objPHPExcel->getActiveSheet()->getComment('A'.$key)->getText()->createTextRun('背景为红色的，全部不能修改！');
            $objPHPExcel->getActiveSheet()->getComment('B'.$key)->getText()->createTextRun('背景为红色的，全部不能修改！');
            $objPHPExcel->getActiveSheet()->getComment('D'.$key)->getText()->createTextRun('背景为红色的，全部不能修改！');
            $objPHPExcel->getActiveSheet()->getStyle( 'A'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle( 'A'.$key)->getFill()->getStartColor()->setARGB('FF993300');
            $objPHPExcel->getActiveSheet()->getStyle( 'B'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle( 'B'.$key)->getFill()->getStartColor()->setARGB('FF993300');
            $objPHPExcel->getActiveSheet()->getStyle( 'D'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle( 'D'.$key)->getFill()->getStartColor()->setARGB('FF993300');
            $objPHPExcel->setActiveSheetIndex(0)->getstyle("A$key:H$key")->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
            $objPHPExcel->getActiveSheet()->getRowDimension($key)->setRowHeight(18);
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$key, $value['id'])
                ->setCellValue('B'.$key, $value['cname'])
                ->setCellValue('C'.$key, '')
                ->setCellValue('D'.$key, $value['price'])
                ->setCellValue('E'.$key, '')
                ->setCellValue('F'.$key, '')
                ->setCellValue('G'.$key, '')
                ->setCellValue('H'.$key, '');
            $key++;
        }


        /*设置数据的边框 手册上写的方法只显示竖线 非常坑爹 所以采用网上搜来的方法*/
        $style_array = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            ));
        $key += 1;
        $objPHPExcel->getActiveSheet()->getStyle('A1:P'.$key)->applyFromArray($style_array);
        //设置填充的样式和背景色
        $objPHPExcel->getActiveSheet()->getStyle( 'A7:H7')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'A7:H7')->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'A1:A3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'A1:A3')->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'B3:B5')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'B3:B5')->getFill()->getStartColor()->setARGB('FF808080');
        // $objPHPExcel->getActiveSheet()->getStyle( 'C2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        // $objPHPExcel->getActiveSheet()->getStyle( 'C2')->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'F3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'F3')->getFill()->getStartColor()->setARGB('FF993300');
        // $objPHPExcel->getActiveSheet()->getStyle( 'D2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        // $objPHPExcel->getActiveSheet()->getStyle( 'D2')->getFill()->getStartColor()->setARGB('FF993300');//业务员
        $objPHPExcel->getActiveSheet()->getStyle( 'D3:E6')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'D3:E6')->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'A'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'A'.$key)->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'C'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'C'.$key)->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'E'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'E'.$key)->getFill()->getStartColor()->setARGB('FF808080');
        $objPHPExcel->getActiveSheet()->getStyle( 'G'.$key)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle( 'G'.$key)->getFill()->getStartColor()->setARGB('FF808080');
        //表尾
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A'.$key, '收货方式')
            ->setCellValue('B'.$key, $row['receivingWay'])
            ->setCellValue('C'.$key, '要求到货时间')
            ->setCellValue('D'.$key, $row['forArrivalGoodsTime'])
            ->setCellValue('E'.$key, '运费承担方')
            ->setCellValue('F'.$key, $row['freightFor'])
            ->setCellValue('G'.$key, '备注')
            ->setCellValue('H'.$key, $row['remark']);

        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension('4')->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension('5')->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension('6')->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension('7')->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension($key-1)->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension($key-2)->setRowHeight(20);/*设置行高*/
        $objPHPExcel->getActiveSheet()->getRowDimension($key-3)->setRowHeight(20);/*设置行高*/
        //设置宽width 由于自适应宽度对中文的支持是个BUG因此坑爹的手动设置了每一列的宽度 这种感觉 if（has（蛋）！=0）{碎();}
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        /*设置表相关的信息*/
        $objPHPExcel->getActiveSheet()->setTitle('北京宏达一甲教育科技有限公司《小学生绘本课堂》发货单'); //活动表的名称
        $objPHPExcel->setActiveSheetIndex(0);//设置第一张表为活动表
        //纸张方向和大小 为A4横向
        $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
        $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);

        //浏览器交互 导出
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$agent['gname'].'--《小学生绘本课堂》发货单  .xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function edit($ids = NULL)
    {
        if($order = $this->model->get(['id'=>$ids,'sorter'=>1]))
        {
            if($this->request->isPost())
            {
                Db::startTrans();
                $param = $this->request->request('row/a');
                $order->receivingWay = $param['receivingWay'];
                $order->forArrivalGoodsTime = time($param['forArrivalGoodsTime']);
                $order->freightFor = $param['freightFor'];
                $order->deliverystatus = 1;
                $order->remark = $param['remark'];

                $dataRow = [];

                foreach ($param['pro'] as $key=>$value)
                {
                    $dataRow[] = ['id'=>$key,'num'=>$value];
                    $rowItem = $this->Orderitem->get(['order_id'=>$order->id,'preproduct_id'=>$key]);
                    $dataUpdate[] = ['id'=>$rowItem->id,'order_id'=>$order->id,'nums'=>$value,'status'=>1];
                }
                if(!$this->Orderitem->saveAll($dataUpdate))
                {
                    Db::rollback();
                    $this->error('数据错误！');
                }
                $agentName = Githouse::get(['dep'=>$order['dep_id']]);
                $resout = gzy_reduce_stock($agentName->id,$dataRow,$this->auth->userid);
                //1 总部仓库
                if(!$resout['status'])
                {
                    Db::rollback();
                    $preRow = Preproduct::get($resout['id']);
                    $this->error($preRow->cname.'库存不足，请联系库房添加库存！');
                }else{
                    //订单修改 发货单id
                    $order->delivery_id = $resout['order_id'];
                    $order->pay = 1;
                    $order->deliverystatus = 3;
                    $order->status = 2;
                    $order->step = 6;
                }
                $order->save();
                //添加操作日志
                $this->Orderlog->create([
                    'order_id'=>$order->id,
                    'userid'=>$this->auth->userid,
                    'username'=>$this->auth->username,
                    'content'=>'操作发货',
                    'type'=>1,
                ]);
                Db::commit();
                $this->success();
            }
            if($order['idCard']){
                $order['idCard_text'] = Admin::userName($order['idCard']);
            }
            //订单详情
            $orderList = $this->Orderitem->alias('a')
                ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
                ->where('a.order_id',$ids)
                ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                ->select();

            $orderlogList = $this->Orderlog->where('order_id',$ids)->select();
            $this->view->assign('orderlogList',$orderlogList);
            $this->view->assign('order',$order);
            $this->view->assign('orderList',$orderList);
        }else{
            $this->error('数据不存在');
        }

        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                  

                    $goods_id = $params['goods']['goods_id'];
                    $params['goods']['goods_id'] = [];
                    foreach ($goods_id as $value)
                    {
                        $params['goods']['goods_id'][] = $value[1];
                    }
                    Db::startTrans();
                    $gift = $this->request->request('gift');
                    unset($params['enter_number']);
                    //等于1 发货半成品  等于2 添加订单
                    if($params['goods']['goods_id'][0])
                    {
                        $params['sorter'] = 1;
                        $params['nb'] = getOrderNo('DL-S');
                        $params['userid'] = $this->auth->userid;
                        $params['deliverydate'] = time($params['deliverydate']);
                        $params['forArrivalGoodsTime'] = time($params['forArrivalGoodsTime']);
                        if($gift == 1)
                        {
                            $params['deliverystatus'] = 3;
                            $params['status'] = 2;
                        }
                        //订单状态
                        unset($params['goods_ids'],$params['type']);
                        $result = $this->model->allowField(true)->save($params);
                        $orderId = $this->model->getLastInsID();
                        $orderItem = [];
                        $dataRow = [];
                        $ministrial = 0;
                        $real_ocean = 0;
                        foreach ($params['goods']['goods_id'] as $index=>$value)
                        {
                            if($params['goods']['goods_num'][$index] >= 1 )
                            {
                                $discount = $params['goods']['discount'][$index];
                                if(($discount * 100) > 100)
                                {
                                    $this->error('请填写正确的商品折扣比例！');
                                }
                                if(!$rowPro = Preproduct::get($value))
                                {
                                    $this->error('商品ID错误！');
                                }
                                if($params['goods']['discount'][$index] == 0.257)
                                {
                                    $ocean = $params['goods']['goods_num'][$index] * 10;
                                }else{
                                    //价格 * 数量 * 折扣 再四舍五入
                                    $ocean = round(($rowPro->price * $params['goods']['goods_num'][$index]) * $params['goods']['discount'][$index],2);
                                    //价格乘以折扣 四舍五入  再乘以数量
                                    //$ocean = round($rowPro->price * $params['goods']['discount'][$index],2) * $params['goods']['goods_num'][$index];
                                }
                                $orderItem[] = [
                                    'preproduct_id' => $value,
                                    'pricing'=>$rowPro->price,
                                    'status'=>$gift == 2 ? 0 : 1,//0 没发货 1发货
                                    'discount'=>$params['goods']['discount'][$index],
                                    'num' => $params['goods']['goods_num'][$index],
                                    'nums'=> $gift == 2 ? 0 : $params['goods']['goods_num'][$index],//等于2  不出库  等于1 半成品出库
                                    'remark' => $params['goods']['remark'][$index],
                                    'order_id' => $orderId,
                                    'ministrial'=>$rowPro->price * $params['goods']['goods_num'][$index],//码洋
                                    'real_ocean'=>$ocean,//实洋
                                ];

                                $ministrial += $rowPro->price * $params['goods']['goods_num'][$index];
                                $real_ocean += $ocean;
                                $dataRow[] = ['id'=>$value,'num'=>$params['goods']['goods_num'][$index]];
                            }else{
                                Db::rollback();
                                $this->error('请选择正确的数量。');
                            }

                        }
                        if($gift == 1)
                        {   $agentName = Githouse::get(['dep'=>$params['dep_id']]);
                            $resout = gzy_reduce_stock($agentName->id,$dataRow,$this->auth->userid);
                            //1 总部仓库
                            if(!$resout['status'])
                            {
                                Db::rollback();
                                $preRow = Preproduct::get($resout['id']);
                                $this->error($preRow->cname.'库存不足，请联系库房添加库存！');
                            }else{
                                //订单修改 发货单id
                                $orderRow = $this->model->get($orderId);
                                $orderRow->order_price = $ministrial;
                                $orderRow->check_order = $real_ocean;
                                $orderRow->delivery_id = $resout['order_id'];
                                $orderRow->status = 2;
                                $orderRow->save();
                            }
                        }
                    }else{
                        Db::rollback();
                        $this->error('请选择下单商品');
                    }
                    //生产订单详情
                    $orderItemRes = $this->Orderitem->saveAll($orderItem,false);
                    if ($result !== false && $orderItemRes !== false) {
                        //订单修改 发货单id
                        $orderRow = $this->model->get($orderId);
                        $orderRow->order_price = $ministrial;
                        $orderRow->check_order = $real_ocean;
                        $orderRow->save();
                        //添加操作日志
                        $this->Orderlog->create([
                            'order_id'=>$orderId,
                            'userid'=>$this->auth->userid,
                            'username'=>$this->auth->username,
                            'content'=>'后台添加完成',
                            'type'=>1,
                        ]);
                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $table = $this->Orderitem->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

        //获取数据
        $data = ['pay'=>1,'deliverystatus'=>3,'status'=>2,'step'=>6,'userid'=>$this->auth->userid];
        $data['orderdate'] = strtotime($currentSheet->getCellByColumnAndRow(1,2)->getValue());
        $data['createtime'] = strtotime($currentSheet->getCellByColumnAndRow(1,2)->getValue());//日期
        // $data['idCard'] = $currentSheet->getCellByColumnAndRow(3,2)->getValue();//业务员身份证 需要验证
        // if(!$data['idCard']) $this->error(__('请填写正确的信息。'));
        // $admin = model('Admin');
        // $user = $admin->get(['userid'=>$data['idCard']]);
        // if(!$user->userid) $this->error(__('请填写正确的业务员身份证信息。'));
        // $data['idCard'] = $user->userid;
        $data['nb'] = getOrderNo('DL-S');
        $data['sorter'] = 1;//分公司
        $data['nameShipper'] = $currentSheet->getCellByColumnAndRow(2,3)->getValue();//发货方名称
        $data['shipperTelephone'] = $currentSheet->getCellByColumnAndRow(2,4)->getValue();//发货方电话
        $data['shipperAddress'] = $currentSheet->getCellByColumnAndRow(2,5)->getValue();//发货方地址
        $data['nameAgent'] = $currentSheet->getCellByColumnAndRow(5,3)->getValue();//代理商名称
        if(!$data['nameAgent']) $this->error(__('请填写正确的分公司信息。'));
        $agentName = Githouse::get(['gname'=>$data['nameAgent']]);
        if(!$agentName) $this->error(__('请填写正确的分公司信息。'));
        $data['nameAgent'] = $agentName->gname;
        $data['dep_id'] = $agentName->dep;
        $data['consignee'] = $currentSheet->getCellByColumnAndRow(5,4)->getValue();//收货人
        $data['consigneeTelephone'] = $currentSheet->getCellByColumnAndRow(5,5)->getValue();//收货人电话
        $data['consigneeAddress'] = $currentSheet->getCellByColumnAndRow(5,6)->getValue();//收货人地址
        $data['receivingWay'] = $currentSheet->getCellByColumnAndRow(1,$allRow)->getValue();//收货方式
        $data['forArrivalGoodsTime'] = strtotime($currentSheet->getCellByColumnAndRow(3,$allRow)->getValue());//要求到货时间
        $data['freightFor'] = $currentSheet->getCellByColumnAndRow(5,$allRow)->getValue();//运费承担
        $data['remark'] = $currentSheet->getCellByColumnAndRow(7,$allRow)->getValue();//备注

        //生成订单
        Db::startTrans(); // 启动事务

        $orderModel = $this->model->create($data);
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 7; $currentRow <= 7; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }

        $insert = [];
        $order_price = 0;
        $check_order = 0;
        $dataRow = [];
        for ($currentRow = 8; $currentRow <= $allRow - 2; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                $values[] = is_null($val) ? '' : trim($val);
            }
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if(isset($row['num']) && isset($row['discount']))
            {
                if($row['num'] > 0)
                {
                    if(!$product = Preproduct::get($row['preproduct_id'])) $this->error(__('插入的商品不存在，请不要修改表格的序号！'));
                    $row['pricing'] = $product->price;
                    //码洋  定价*数量  实洋 码洋*折扣
                    $row['order_id'] = $orderModel->id;
                    $row['nums'] = $row['num'];
                    $row['status'] = 1;
                    $row['ministrial'] = $row['nums'] * $row['pricing'];
                    if($row['discount'] == 0.257)
                    {
                        $row['real_ocean'] = $row['num'] * 10;
                    }else{
                        //
                        //价格 * 数量 * 折扣 再四舍五入
                        $row['real_ocean'] = round(($row['pricing'] * $row['nums'] ) * $row['discount'],2);
                        //价格乘以折扣 四舍五入  再乘以数量
//                        $row['real_ocean'] = round($row['pricing'] * $row['discount'],2) * $row['nums'];
                    }
                    $insert[] = $row;
                    $order_price += $row['ministrial'];
                    $check_order += $row['real_ocean'];
                    $dataRow[] = ['id'=>$row['preproduct_id'],'num'=>$row['nums']];
                }
            }
        }
        if (!$insert) {
            $this->error(__('没有可插入的数据！'));
        }

        //1 总部仓库
        $resout = gzy_reduce_stock($agentName->id,$dataRow,$this->auth->userid);
        if(!$resout['status'])
        {
            Db::rollback();
            $preRow = Preproduct::get($resout['id']);
            $this->error($preRow->cname.'库存不足，请联系库房添加库存！');
        }else{
            //订单修改 发货单id
            $orderModel->delivery_id = $resout['order_id'];
        }
        try {
            //1 总部库存
            $orderModel->order_price = $order_price;
            $orderModel->check_order = $check_order;
            $orderModel->save();
            $this->Orderitem->saveAll($insert);
            Db::commit();
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
            Db::rollback();
        }

        $this->success();
    }

}
